package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.IUserMapper;
import com.example.demo.param.dto.user.UpdateAdminDto;
import com.example.demo.service.ITokenService;
import com.example.demo.service.IUserService;
import com.example.demo.util.Judge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired private IUserMapper userMapper;
    @Autowired private ITokenService tokenService;

    @Override
    public User userLog(String username , String password , Integer role) throws ServiceException {
        if (Judge.isNull(username) || Judge.isNull(password)){
            throw new ServiceException("请提供正确的用户名和密码！");
        }
        User user = this.userMapper.getUserByName(username);
        if (user == null){
            throw new ServiceException("请先注册账号！");
        }
        if (user.getRole() != role){
            throw new ServiceException("您的权限不足！");
        }
        String md5 = Judge.md5(password);
        if (!md5.equals(user.getPassword())){
            throw new ServiceException("密码错误！");
        }
        String token = this.tokenService.insert(user.getUserId());
        user.setPassword(token);
        return user;
    }

    @Override
    public Boolean userReg(String username, String password , Integer role) throws ServiceException {
        if (Judge.isNull(username) || Judge.isNull(password)){
            throw new ServiceException("请提供正确的用户名和密码！");
        }
        String usernameRegex = "^.{1,10}";
        String passwordRegex = "^[a-zA-Z0-9]{6,12}";

        Matcher usernameMatcher = Pattern.compile(usernameRegex).matcher(username);
        Matcher passwordMatcher = Pattern.compile(passwordRegex).matcher(password);

        if (!usernameMatcher.matches()){
            throw new ServiceException("您输入的用户名格式有误!");
        }
        if (!passwordMatcher.matches()){
            throw new ServiceException("您输入的密码名格式有误!");
        }
        String md5 = Judge.md5(password);
        if (this.userMapper.insert(Judge.getUUID(),username,md5,role,0,new Date()) != 1){
            throw new ServiceException("注册失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateImformation(String userId, String username, Integer gender, Date birthday, String produce) throws ServiceException{
        User user = this.userMapper.getById(userId);
        if (user == null || user.getRole() == 2){
            throw new ServiceException("未找到该用户");
        }
        if(Judge.isNotNull(username)){
            User user1 = this.userMapper.getUserByName(username);
            if(user1 != null && !user1.getUserId().equals(userId)){
                throw new ServiceException("对不起，该用户名已存在！");
            }
            user.setUsername(username);
        }
        if(gender != null){
            if(gender < 0 || gender > 2){
                gender = 2;
            }
            user.setGender(gender);
        }
        if(birthday != null){
            user.setBirthday(birthday);
        }
        if(Judge.isNotNull(produce)){
            user.setProduce(produce);
        }
        Integer affect = this.userMapper.updateImformation(
                user.getUserId(),user.getUsername(),user.getGender(),user.getBirthday(),user.getProduce());
        if (affect != 1){
            throw new ServiceException("修改个人信息失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean updatePassword(String userId, String password, String newPassword) {
        if (Judge.isNull(newPassword) || Judge.isNull(password)){
            throw new ServiceException("请务必完善必填项！");
        }
        User user = this.userMapper.getById(userId);
        if (user == null || user.getRole() == 2){
            throw new ServiceException("没有这个用户");
        }
        password = Judge.md5(password);
        if (!user.getPassword().equals(password)){
            throw new ServiceException("原密码错误！");
        }
        Integer affect = this.userMapper.updatePassword(userId,Judge.md5(newPassword));
        if (affect != 1){
            throw new ServiceException("修改密码失败！");
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateAdminPassword(UpdateAdminDto dto) throws ServiceException {
        this.tokenService.isRoleType(dto.getToken(), 2);
        User admin = this.userMapper.getById(dto.getId());
        if(admin == null || admin.getRole() != 2){
            throw new ServiceException("没有这个管理员");
        }
        admin.setPassword(Judge.md5(dto.getPassword()));
        if(this.userMapper.updatePassword(admin.getUserId(), admin.getPassword()) != 1){
            throw new ServiceException("修改失败");
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean deleteAdmin(String token, String id) throws ServiceException {
        if(Judge.isNull(token) || Judge.isNull(id)){
            throw new ServiceException("请完善必填项");
        }
        String uid = this.tokenService.isRoleType(token, 2);
        if(id.equals(uid)){
            throw new ServiceException("不能自己删除自己");
        }
        User admin = this.userMapper.getById(id);
        if(admin == null || admin.getRole() != 2){
            throw new ServiceException("没有这个管理员");
        }
        admin.setIsDelete(1);
        if(this.userMapper.delete(admin.getUserId(), admin.getIsDelete()) != 1){
            throw new ServiceException("删除失败");
        }
        return Boolean.TRUE;
    }
}
